<template>
  <div class="pagination">
    <button :disabled="currentPageno === 1" @click="$emit('changeNo',currentPageno - 1)">上一页</button>
    <button v-if="startEnd.start > 1" @click="$emit('changeNo',1)">1</button>
    <button v-if="startEnd.start > 2">···</button>

    <button 
        :class="{active:page === currentPageno}" 
        v-for="page in startEnd.end" 
        v-if="page >= startEnd.start" 
        :key="page"
        @click="$emit('changeNo',page)"
    >{{page}}</button>

    <button v-if="startEnd.end < totalPageNo - 1" >···</button>
    <button v-if="startEnd.end < totalPageNo" @click="$emit('changeNo',totalPageNo)">{{ totalPageNo }}</button>
    <button :disabled="currentPageno === totalPageNo" @click="$emit('changeNo',currentPageno + 1)">下一页</button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: {
    //显示当前页
    currentPageno: {
      type: Number,
      require: true,
    },
    //每页显示数量
    pageSize: {
      type: Number,
      require: true,
    },
    // 显示连续页数
    continueNum: {
      type: Number,
      default: 5,
    },
    //显示数据的总条数
    total: {
      type: Number,
      default: 0,
    },
  },
  computed: {
    totalPageNo() {
      // 计算属性计算    总条数   / 每页显示数量   =  总页数  (每页显示数量一般都奇数,所以需要向上取整)
      return Math.ceil(this.total / this.pageSize);
    },
    startEnd() {
      //  连续页数       当前页         总页数
      let { continueNum, currentPageno, totalPageNo } = this;
      let start = 0,end = 0;
      //总页数 < 连续页数
      if (totalPageNo < continueNum) {
        start = 1;
        end = totalPageNo;
      } else {
        //开始位置 = 当前页 - 向下取整的 总页数/2
        start = currentPageno - Math.floor(continueNum / 2);
        //结束位置 = 当前页 + 向下取整的 总页数/2
        end = currentPageno + Math.floor(continueNum / 2);
        //起始位置 < 1
        if (start < 1) {
          start = 1;
          end = continueNum;
        }
        // 结束位置 > 总页数
        if (end > totalPageNo) {
          // 结束位置等于中页数
          end = totalPageNo;
          // 开始位置等于总页数-连续页数 + 1
          start = totalPageNo - continueNum + 1;
        }
      }
      return { start, end };
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>